package yunjiao.javatutorials.lang.concurrent;

import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveTask;

/**
 * 数组求和（RecursiveTask）
 *
 * @author yangyunjiao
 */
public class SumTask extends RecursiveTask<Long> {
    private static final int THRESHOLD = 10000; // 阈值，小于此值不再拆分
    private final long[] array;
    private final int start;
    private final int end;

    public SumTask(long[] array, int start, int end) {
        this.array = array;
        this.start = start;
        this.end = end;
    }

    @Override
    protected Long compute() {
        // 如果任务足够小，直接计算
        if (end - start <= THRESHOLD) {
            long sum = 0;
            for (int i = start; i < end; i++) {
                sum += array[i];
            }
            return sum;
        } else {
            // 拆分任务
            int mid = (start + end) / 2;
            SumTask leftTask = new SumTask(array, start, mid);
            SumTask rightTask = new SumTask(array, mid, end);

            // 异步执行左半部分
            leftTask.fork();

            // 同步执行右半部分，并等待左半部分完成
            long rightResult = rightTask.compute();
            long leftResult = leftTask.join();

            return leftResult + rightResult;
        }
    }

    public static void main(String[] args) {
        // 创建测试数组
        long[] array = new long[1000000];
        for (int i = 0; i < array.length; i++) {
            array[i] = i + 1;
        }

        // 创建ForkJoinPool
        try(ForkJoinPool pool = new ForkJoinPool()) {

            long start = System.currentTimeMillis();
            // 创建任务
            SumTask task = new SumTask(array, 0, array.length);

            // 执行任务并获取结果
            long result = pool.invoke(task);

            System.out.println("计算耗时（毫秒）: " + (System.currentTimeMillis() - start));
            System.out.println("计算结果: " + result);
            System.out.println("期望结果: " + (1000000L * 1000001L / 2));


        }

    }
}
